package com.huawei.translate.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HttpUtils {

    private static final Logger LOG = Logger.getLogger(HttpUtils.class);

    private static final String CHARSET = "utf-8";

    public static String getContentFromInputStream(InputStream inputStream) {
        try {
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(inputStream, CHARSET));
            StringBuffer result = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception exception) {
            return null;
        }
    }

    public static CloseableHttpClient makeHttpClient(String proxyHost, int proxyPort, String proxyUserName, String proxyPassword) {
        if (StringUtils.isBlank(proxyHost)) {
            LOG.info("Create Http Client with no proxy");
            return HttpClients.createDefault();
        } else {
            LOG.info("Create Http Client with proxy: " + proxyHost);
            return makeProxyHttpClient(proxyHost, proxyPort, proxyUserName, proxyPassword);
        }
    }

    private static CloseableHttpClient makeProxyHttpClient(String proxyServer, int proxyPort, String proxyUserName, String proxyPassword) {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();


        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(connectionManager);
        // Set proxy if needed
        HttpHost proxyHost = new HttpHost(proxyServer, proxyPort);
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
        clientBuilder.setRoutePlanner(routePlanner);

        // Select and configure the properties you are interested in
        RequestConfig config = RequestConfig.custom()
                .setProxy(proxyHost)
                .setRedirectsEnabled(true)
                .setMaxRedirects(5)
                .setConnectTimeout(5 * 1000)
                .setConnectionRequestTimeout(5 * 1000)
                .setSocketTimeout(5 * 1000)
                .build();

        // set proxy authentication as needed
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(proxyServer, proxyPort),
                new UsernamePasswordCredentials(proxyUserName, proxyPassword));


        clientBuilder.setDefaultCredentialsProvider(credsProvider);
        clientBuilder.setDefaultRequestConfig(config);

        // Now build and return the client
        return clientBuilder.build();
    }
}
